package com.zrwl.poscloud.xo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrwl.poscloud.base.entity.Dept;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.utils.DeptUtil;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.commons.utils.StringUtils;
import com.zrwl.poscloud.xo.global.MessageConf;
import com.zrwl.poscloud.xo.global.SQLConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.mapper.DeptMapper;
import com.zrwl.poscloud.xo.service.DeptService;
import com.zrwl.poscloud.xo.vo.DeptVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 商户机构 服务实现类
 *
 * @author 刘思童 AutoGenerate
 * @date 2021-02-02
 */
@Service
public class DeptServiceImpl extends SuperServiceImpl<DeptMapper, Dept> implements DeptService {

    @Autowired
    private DeptService deptService;
    @Resource
    private DeptMapper deptMapper;

    @Override
    public IPage<Dept> getPageList(DeptVO deptVO) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(deptVO.getKeyword()) && !StringUtils.isEmpty(deptVO.getKeyword().trim())) {
            queryWrapper.like("name", deptVO.getKeyword().trim());
        }
        if (StringUtils.isNotEmpty(deptVO.getSuperCompanyCode()) && !StringUtils.isEmpty(deptVO.getSuperCompanyCode().trim())) {
            queryWrapper.likeRight("company_code", DeptUtil.getLatestCompnay(deptVO.getSuperCompanyCode()));
            queryWrapper.ne("company_code", deptVO.getSuperCompanyCode());
        }
        Page<Dept> page = new Page<>();
        page.setCurrent(deptVO.getCurrentPage());
        page.setSize(deptVO.getPageSize());
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc("company_code");
        IPage<Dept> pageList = deptService.page(page, queryWrapper);
        List<Dept> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<Dept> getAllList(DeptVO deptVO) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        List<Dept> list = deptService.list(queryWrapper);
        return list;
    }

    @Override
    public String add(DeptVO deptVO){
        Dept entity = new Dept();
        BeanUtils.copyProperties(deptVO, entity, SysConf.STATUS);
        //通过父级机构，获得当前兄弟机构的最大编码，然后加1 并补零 得到新的编码
        entity.setCompanyCode(deptService.getCode(deptVO));
        //根据code 设置机构的level字段
        entity.setLevel(Integer.parseInt(DeptUtil.getCompanyLevel(entity.getCompanyCode())));
        entity.insert();
        deptVO.setUid(entity.getUid());
        deptVO.setCompanyCode(entity.getCompanyCode());
        deptVO.setLevel(entity.getLevel());
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String edit(DeptVO deptVO) {
        Dept entity = deptService.getById(deptVO.getUid());
        BeanUtils.copyProperties(deptVO, entity);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String delete(DeptVO deptVO) {
        Dept entity = deptService.getById(deptVO.getUid());
        entity.setStatus(EStatus.DISABLED);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public Void setChildrenList(DeptVO deptVO) {
        log.debug(deptVO.getName() + "读取子机构");
        deptVO.setSuperCompanyCode(DeptUtil.getLatestCompnay(deptVO.getCompanyCode()));
        List<DeptVO> childrenList = deptMapper.selectChildren(deptVO);
        deptVO.setChildrenList(childrenList);
        for (int i = 0; i < childrenList.size(); i++) {
            setChildrenList(childrenList.get(i));
        }
        return null;
    }

    @Override
    public Void setChildrenList(DeptVO deptVO, List<String> checkList, Map<String, DeptVO> deptMap) {
        log.debug(deptVO.getName() + "读取子机构");
        deptVO.setSuperCompanyCode(DeptUtil.getLatestCompnay(deptVO.getCompanyCode()));
        List<DeptVO> childrenList = deptMapper.selectChildren(deptVO);
        deptVO.setChildrenList(childrenList);
        for (int i = 0; i < childrenList.size(); i++) {
            for (String item : checkList) {
                childrenList.get(i).setPermission(true);
                if (item.equals(childrenList.get(i).getUid())) {
                    childrenList.get(i).setPermission(false);
                    break;
                }
            }
            DeptVO child = childrenList.get(i);
            child.setSuperCompanyName(deptVO.getName());
            child.setSuperCompanyFullName(deptVO.getSuperCompanyFullName() + "/" + deptVO.getName());
            deptMap.put(child.getCompanyCode(), child);
            setChildrenList(child, checkList, deptMap);
        }
        return null;
    }
    @Override
    public String getCode(DeptVO deptVO) {
        //根据superCode获取最大子节点
        String superCompanyCode = DeptUtil.getLatestCompnay(deptVO.getSuperCompanyCode());
        String maxCode = deptMapper.selectMaxChildCode(superCompanyCode);
        if (maxCode == null) {
            return DeptUtil.getCompanyFull(superCompanyCode + "001");
        } else {
            long codeValue = Long.parseLong(maxCode.substring(5, superCompanyCode.length() + 3));
            String zeroStart = "0000" + (++codeValue);
            return DeptUtil.getCompanyFull(superCompanyCode + zeroStart.substring(zeroStart.length() - 3));
        }
    }
    @Override
    public Dept getDeptByCode(String code) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_code", code);
        queryWrapper.ne(SQLConf.STATUS,EStatus.DISABLED);
        queryWrapper.last("limit 1");
        return deptService.getOne(queryWrapper);
    }

    @Override
    public Dept getDeptByName(String superDeptName) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", superDeptName);
        queryWrapper.ne(SQLConf.STATUS,EStatus.DISABLED);
        queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
        queryWrapper.last("limit 1");
        return deptService.getOne(queryWrapper);
    }

    @Override
    public String getCompanyNameByCompanyCode(String companyCode) {
        return deptMapper.getCompanyNameByCompanyCode(companyCode);
    }

    public boolean exitName(String name, String companyCode) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name.trim());
        queryWrapper.likeRight("company_code", DeptUtil.getLatestCompnay(companyCode.trim()));
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        Page<Dept> page = new Page<>();
        page.setCurrent(1);
        page.setSize(1);
        IPage<Dept> pageList = deptService.page(page, queryWrapper);
        if (pageList.getRecords().size() > 0) {
            return true;
        } else {
            return false;
        }
    }
}
